/// @Classname : HcAvatarGroup
/// @Author : HalfCity
/// @Time : 2023-04-21 15:33
/// @Description : 头像组
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:hc_ui/constants/hc_size.dart';
import 'package:hc_ui/widget/avatar/hc_avatar.dart';
import 'package:hc_ui/widget/avatar_group/hc_avatar_grid_group.dart';

import '../../constants/hc_color.dart';

class HcAvatarStackGroup extends StatelessWidget {
  //图片的列表
  final List<HcAvatarItem> avatarList;

  //是否展示更多的 Icon
  final bool showMoreIcon;

  //边框颜色
  final Color borderColor;

  //边框宽度
  final double borderWidth;

  //是否反方向
  final bool reverse;

  //缩进大小
  final double spaceWidth;

  //子组件大小
  final double size;

  //子组件的圆角矩形
  final double radius;

  const HcAvatarStackGroup(
      {super.key,
      required this.avatarList,
      this.showMoreIcon = false,
      this.borderColor = HcColor.defaultBorderColor,
      this.borderWidth = HcSize.defaultAvatarBorderWidth,
      this.reverse = false,
      this.spaceWidth = HcSize.defaultAvatarSpaceWidth,
      this.size = HcSize.defaultAvatarSize,
      this.radius = HcSize.defaultMaxRadius});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      //获取最大宽度
      double maxWidth = constraints.maxWidth;
      //每个子组件大小
      double widgetWidth = size + borderWidth * 2;
      //最大可展示数字
      int num = (maxWidth - widgetWidth) ~/ (spaceWidth * widgetWidth);
      //构建列表
      List<HcAvatarItem> finalList = avatarList;
      if (finalList.length >= num) {
        finalList = avatarList.sublist(
            0, showMoreIcon ? num : min(finalList.length, num + 1));
      }
      if (showMoreIcon) {
        finalList.add(HcAvatarItem(icon: Icons.more_horiz_outlined));
      }
      if (reverse) {
        finalList = finalList.reversed.toList();
      }
      return SizedBox(
        height: widgetWidth,
        child: Stack(
          children: finalList.map((HcAvatarItem item) {
            return Positioned(
                left: widgetWidth *
                    spaceWidth *
                    (reverse
                        ? (finalList.length - finalList.indexOf(item) - 1)
                        : finalList.indexOf(item)),
                child: HcAvatar(
                  size: size,
                  radius: radius,
                  backgroundImageUrl: item.backgroundImageUrl,
                  foregroundImageUrl: item.foregroundImageUrl,
                  backgroundColor: item.backgroundColor,
                  borderWidth: borderWidth,
                  borderColor: borderColor,
                  name: item.name,
                  themeData: item.themeData,
                  child: item.icon != null ? Icon(item.icon) : null,
                ));
          }).toList(),
        ),
      );
    });
  }
}
